<template>
  <div>
    <el-dialog
      :show-close="false"
      v-model="dialogVisible"
      width="500"
      :title="trademarkForm.id ? '修改品牌' : '添加品牌'"
      :before-close="handleClose"
    >
      <el-form
        ref="formInstance"
        label-width="auto"
        style="max-width: 600px"
        :rules="rules"
        :model="trademarkForm"
      >
        <el-form-item label-width="100px" label="品牌名称" prop="tmName">
          <el-input v-model="trademarkForm.tmName" />
        </el-form-item>
        <el-form-item label-width="100px" label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkForm.logoUrl"
              :src="trademarkForm.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialog">取消</el-button>
          <el-button type="primary" @click="updateTrademark">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-card>
      <el-button
        @click="handleTradeMark"
        type="primary"
        icon="Plus"
        v-has="'btn.Trademark.add'"
      >
        添加品牌
      </el-button>
      <el-table
        class="trademark_table"
        :data="tradeMarkList"
        style="width: 100%"
      >
        <el-table-column prop="date" label="序号" width="80" type="index" />
        <el-table-column prop="tmName" label="品牌名称" width="180" />
        <el-table-column prop="address" label="品牌LOGO">
          <template #="{ row, $index }">
            <img
              :src="row.logoUrl"
              alt="暂无图片"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="address" label="品牌操作">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              icon="Edit"
              @click="editTrademark(row)"
              v-has="'btn.Trademark.update'"
            />

            <el-popconfirm
              @confirm="deleteTrademark(row)"
              title="确定删除该品牌吗？"
            >
              <template #reference>
                <el-button
                  v-has="'btn.Trademark.remove'"
                  type="primary"
                  icon="Delete"
                  color="orange"
                />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 4, 5, 6]"
        :size="size"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import { nextTick, reactive, ref } from 'vue'
import type { ComponentSize } from 'element-plus'
import { onMounted } from 'vue'
import {
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/treademark'
import { getTradeMark } from '@/api/product/treademark'
import { ITrademarkParam } from '@/api/product/treademark/type'
import trademarkService from '@/views/product/trademark/trademark.service'
let currentPage = ref<number>(1)
let tradeMarkList = ref([])

let pageSize = ref<number>(3)
const size = ref<ComponentSize>('default')
let total = ref(400)
let dialogVisible = ref<boolean>(false)
let trademarkForm = reactive<ITrademarkParam>({
  id: '',
  tmName: '',
  logoUrl: '',
})
const handleTradeMark = () => {
  dialogVisible.value = true
  nextTick(() => {
    clearFormValidate()
  })
}
let { rules, formInstance, clearFormValidate } = trademarkService()
const reqTradeMarkList = async () => {
  try {
    let result = await getTradeMark(currentPage.value, pageSize.value)
    if (result.code == 200) {
      total.value = result.data.total
      tradeMarkList.value = result.data.records
      console.log(tradeMarkList)
    }
  } catch (error) {
    console.log(error)
  }
}
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  currentPage.value = 1
  reqTradeMarkList()
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  reqTradeMarkList()
}
const editTrademark = (trademark) => {
  dialogVisible.value = true
  trademarkForm.id = trademark.id
  trademarkForm.logoUrl = trademark.logoUrl
  trademarkForm.tmName = trademark.tmName
  console.log(trademark)
}
const deleteTrademark = async (trademark) => {
  console.log(trademark)
  try {
    let result = await reqDeleteTrademark(trademark.id)
    if (result.code == 200) {
      reqTradeMarkList()
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    } else {
      ElMessage({
        type: 'error',
        message: result.data,
      })
    }
  } catch (error) {
    console.log(error)
  }
}
onMounted(async () => {
  reqTradeMarkList()
})

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  trademarkForm.logoUrl = response.data
  formInstance.value.clearValidate('logoUrl')
}
const cancelDialog = () => {
  clearTrademarkForm()
  clearFormValidate()
  dialogVisible.value = false
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/png' ||
    rawFile.type == 'gif'
  ) {
    if (rawFile.size / 1024 / 1024 > 4) {
      ElMessage.error(' 图片大小不能超过4MB!')
      return false
    } else {
      return true
    }
  } else {
    ElMessage.error('只能上传图片类型!')
    return false
  }
}
const updateTrademark = async () => {
  try {
    await formInstance.value.validate()
    let result = await reqAddOrUpdateTrademark(trademarkForm)
    clearTrademarkForm()
    if (result.code == 200) {
      ElMessage({
        type: 'success',
        message: trademarkForm.id ? '修改成功' : '添加成功',
      })
      reqTradeMarkList()
      dialogVisible.value = false
    }
  } catch (error) {
    console.log(error)
  }
}

const clearTrademarkForm = () => {
  trademarkForm.logoUrl = ''
  trademarkForm.tmName = ''
  trademarkForm.id = ''
}

const handleClose = (done: () => void) => {
  clearTrademarkForm()
}
</script>

<style lang="scss" scoped>
.trademark_table {
  margin: 20px 0;
}
</style>
